/*
 * @Author: xuetao 3168581151@qq.com
 * @Date: 2025-01-23
 * @LastEditors: xuetao 3168581151@qq.com
 * @LastEditTime: 2025-02-08
 * @Description: 静态服务类，权限认证，初始化用户信息
 */
import 'package:chat_client/services/contact_service.dart';
import 'package:dio/dio.dart';
import 'package:image_picker/image_picker.dart';
import 'package:chat_client/utils/image_picker_helper.dart'; // 引入封装的图片选择工具类
import 'package:chat_client/services/api_service.dart';
import 'package:chat_client/repositories/auth_repository.dart';

import 'package:chat_client/services/user_service.dart';

class AuthService {
  // 单例模式
  AuthService._internal();
  static final AuthService _instance = AuthService._internal();
  static AuthService get instance => _instance;

  // api 请求服务
  final ApiService apiService = ApiService.instance;
  final AuthRepository authRepository = AuthRepository.instance;
  final UserService _userService = UserService.instance;
  final ContactService _contactService = ContactService.instance;

  /// 用户注册
  Future<bool> register({
    required String nickName,
    required String password,
    required String phoneNumber,
    required XFile? imageFile,
  }) async {
    MultipartFile? avatarFile;

    try {
      if (imageFile != null) {
        avatarFile = await ImagePickerHelper.convertXFileToMultipart(imageFile);
      }

      final formData = FormData.fromMap({
        'nickname': nickName,
        'password': password,
        'phoneNumber': phoneNumber,
        if (avatarFile != null) 'avatar': avatarFile,
      });

      final registerResponse =
          await apiService.postFormData('/user/register', formData);
      final username = registerResponse['data']['username']; //提取响应中的用户名
      // 注册成功直接登录
      return await login(username, password);
    } catch (e) {
      if (e is ApiError) {
        rethrow; // 有响应体的错误，重新抛出
      }
      return false;
    }
  }

  /// 登录
  Future<bool> login(String username, String password) async {
    try {
      final response = await apiService.post('/user/login', {
        'username': username,
        'password': password,
      });

      // 使用 AuthRepository 存储认证信息
      await authRepository.setAuthInfo(
        token: response['data']['token'],
        username: username,
        password: password,
      );

      final isStore =
          await authRepository.isLocalStore(initAllInfo); // 验证登录并储存所有信息
      if (!isStore) return false;

      return true;
    } catch (e) {
      if (e is ApiError) {
        rethrow; // 有响应体的错误，重新抛出
      }
      return false;
    }
  }

  /// 检查登录状态并尝试自动重连
  Future<bool> reconnect() async {
    // 获取 token
    final token = AuthRepository.token;
    //token 失效
    if (token == null || token.isEmpty || await _verifyToken()) {
      final certificateInfo = await authRepository.getLoginCertificate();

      // 自动重新登录
      final username = certificateInfo['username'];
      final password = certificateInfo['password'];
      if (username != null && password != null) {
        return await login(username, password);
      } else {
        return false;
      }
    }
    return true;
  }

  /// 注销登录
  Future<bool> logout() async {
    // 清除 preferences 中的认证信息
    await authRepository.clearAuthInfo();
    // 清除本地储存的所有信息
    // HiveService.closeAllBoxes();
    return true;
  }

  // 验证token是否有效
  _verifyToken<bool>() async {
    try {
      final response = await apiService.get('/user/verifyToken');
      return response['data']['access'] == true;
    } catch (e) {
      return false;
    }
  }

  // 初始化储存所有信息
  Future<void> initAllInfo() async {
    // 获取远程用户个人信息储存到本地
    await _userService.getRemoteUserInfo();
    // 获取远程好友申请数据到本地
    await _contactService.getRemoteFriendRequestList();
  }
}
